<?php

namespace App\Http\Controllers\Wechat;

use App\Models\UserLibraryInfo;
use App\Models\VolunteerApply;
use App\Models\VolunteerApplyIntention;
use App\Models\VolunteerApplyTime;
use App\Models\VolunteerNotice;
use App\Models\VolunteerPosition;
use App\Models\VolunteerServiceIntention;
use App\Models\VolunteerServiceTime;
use App\Validate\VolunteerValidate;
use Illuminate\Support\Facades\DB;

/**
 * 志愿者服务
 */
class VolunteerController extends CommonController
{
    public $model = null;
    public $volunteerPositionModel = null;
    public $validate = null;

    public function __construct()
    {
        parent::__construct();

        $this->model = new VolunteerApply();
        $this->volunteerPositionModel = new VolunteerPosition();
        $this->validate = new VolunteerValidate();
    }

    /**
     * 获取志愿者须知
     * @param token 用户登录信息
     */
    public function getVolunteerNotice()
    {
        $volunteerNoticeModel = new VolunteerNotice();
        $res = $volunteerNoticeModel->select('content')->where('id', 1)->first();

        //增加行为分析
        $appInviteCodeBehaviorModel = new  \App\Models\AppInviteCodeBehavior();
        $appInviteCodeBehaviorModel->add(22);

        if (!$res) {
            return $this->returnApi(203, "暂无数据");
        }
        $res = $res->toArray();
        //是否已经上传过志愿者信息
        $user_id = $this->request->user_info['id'];
        $volunteerInfo = $this->model->detail(null, $user_id);
        $res['is_volunteer'] = $volunteerInfo ? true : false;
        //是否需要绑定读者证
        $position_info = VolunteerPosition::select(['is_reader', 'real_info', 'real_info_must', 'is_play'])->where('id', 1)->where('is_del', 1)->first(); //打卡是否需要绑定读者证  1 是  2 否
        $close_msg = '志愿者功能已关闭，暂不能操作！';
        if (!empty($position_info)) {
            $res['is_play'] = $position_info['is_play'];
            $res['is_reader'] = $position_info['is_reader'];
            // $res['real_info'] = $position_info['real_info'];
            // $res['real_info_must'] = $position_info['real_info_must'];

            $res['close_msg'] = $position_info['is_play'] == 2 ? $close_msg : '';

            $real_info_arr = $this->volunteerPositionModel->volunteerApplyParam(); //获取所有的数据
            $res['real_info'] = $this->getRealInfoArray($position_info['real_info'], $real_info_arr);
            $res['real_info_must'] = $this->getRealInfoArray($position_info['real_info_must'], $real_info_arr);
        } else {
            $res['is_reader'] = null;
            $res['real_info'] = null;
            $res['real_info_must'] = null;
            $res['is_play'] = 2;
            $res['close_msg'] = $close_msg;
        }
        return $this->returnApi(200, "获取成功", true, $res);
    }

    /**
     * 参加志愿者所需下拉选项(用于下拉框选择)
     * node 类型 1 服务意向  2 服务时间 3 教育程度 4 健康状态 5 性别    多个参数 自由组合，比如都需要则node为 12345
     */
    public function getPullFilterList()
    {
        $node = request()->input('node');
        if (empty($node)) {
            return $this->returnApi(200, "获取成功", true, null);
        }
        $node = str_split($node);

        $volunteerApplyModel = new VolunteerApply();

        $data = [];
        if (in_array(1, $node)) {
            $data['service_intention'] = VolunteerServiceIntention::getServiceIntentionAll();
        }
        if (in_array(2, $node)) {
            $data['service_time'] = VolunteerServiceTime::getServiceTimeAll();
        }
        if (in_array(3, $node)) {
            $degree = $volunteerApplyModel->getDegree(); //教育程度
            foreach ($degree as $key => $val) {
                $data['degree'][$key - 1]['id'] = $key;
                $data['degree'][$key - 1]['name'] = $val;
            }
        }
        if (in_array(4, $node)) {
            $health = $volunteerApplyModel->getHealth(); //健康状态
            foreach ($health as $key => $val) {
                $data['health'][$key - 1]['id'] = $key;
                $data['health'][$key - 1]['name'] = $val;
            }
        }
        if (in_array(5, $node)) {
            $sex = $volunteerApplyModel->getSex(); //性别
            foreach ($sex as $key => $val) {
                $data['sex'][$key - 1]['id'] = $key;
                $data['sex'][$key - 1]['name'] = $val;
            }
        }

        return $this->returnApi(200, "获取成功", true, $data);
    }

    /**
     * 志愿者报名参数(对应后台选择的参数)
     */
    public function volunteerApplyParam()
    {
        $data = $this->volunteerPositionModel->volunteerApplyParam();
        return $this->returnApi(200, "获取成功", true, $data);
    }

    /**
     * 志愿者详情
     * @param token int 用户登录信息
     */
    public function volunteerDetail()
    {
        $user_id = $this->request->user_info['id'];

        $res = $this->model->detail(null, $user_id);

        if (!$res) {
            return $this->returnApi(203, "暂无数据");
        }

        return $this->returnApi(200, "获取成功", true, $res->toArray());
    }


    /**
     * 添加、修改或过期后重新提交用户志愿者信息  （修改后，自动提交到后台审核）
     * @param token int 用户登录信息
     * @param username int 用户姓名
     * @param tel int   联系电话
     * @param sex int  性别
     * @param id_card int  身份证号码
     * @param birth int  生日
     * @param address int  地址
     * @param school int  毕业院校
     * @param major int  学历
     * @param specialty int  个人特长
     * @param nation int  民族
     * @param politics int  政治面貌
     * @param health int  健康状态
     * @param unit int  工作单位
     * @param degree int  教育程度
     * @param intro int  个人简介
     * @param intention_id int  服务意向id   多个 逗号拼接
     * @param times_id int  服务时间id  多个逗号拼接
     */
    public function volunteerApply()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('wx_volunteer_apply')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }
        $user_id = $this->request->user_info['id'];
        // $account_id = $this->request->user_info['account_id'];

        $positionInfo = $this->volunteerPositionModel->detail(1);
        if (empty($positionInfo)) {
            return $this->returnApi(203, "参数错误");
        }
        if ($positionInfo->is_play == 2) {
            return $this->returnApi(201, "志愿者功能已关闭，暂不能申请");
        }

        $account_id = null;
        if ($positionInfo->is_reader == 1) {
            //判断读者证号密码是否正确 和是否绑定读者证
            $userLibraryInfoModel = new UserLibraryInfo();

            $account_lib_info = $userLibraryInfoModel->checkAccountPwdIsNormal($user_id);
            if (is_string($account_lib_info)) {
                return $this->returnApi(204, $account_lib_info);
            }
            $account_id = $account_lib_info['id'];
        }


        $real_info_must = $positionInfo['real_info_must'];
        $real_info_must = explode('|', $real_info_must);
        $volunteerApplyParam = $this->volunteerPositionModel->volunteerApplyParam();

        $data = $this->request->all();

        //验证必填参数
        for ($i = 1; $i < 16; $i++) {
            if (in_array($i, $real_info_must)) {
                if (empty($data[$volunteerApplyParam[$i - 1]['field']])) {
                    return $this->returnApi(201, $volunteerApplyParam[$i - 1]['name'] . "不能为空");
                }
                if ($i == 2 && !in_array($data[$volunteerApplyParam[$i - 1]['field']], [1, 2])) {
                    return $this->returnApi(201, '性别格式不正确');
                }
                if ($i == 3 && strlen($data[$volunteerApplyParam[$i - 1]['field']]) != 10) {
                    return $this->returnApi(201, '生日格式不正确，格式为：xxxx-xx-xx');
                }
                if ($i == 4 && !is_legal_no($data[$volunteerApplyParam[$i - 1]['field']])) {
                    return $this->returnApi(201, '身份证号码格式不正确');
                }
                if ($i == 8 && !verify_tel($data[$volunteerApplyParam[$i - 1]['field']])) {
                    return $this->returnApi(201, '电话号码格式不正确');
                }
            }
        }
        DB::beginTransaction();
        try {
            $intention_id = $this->request->intention_id;
            $times_id = $this->request->times_id;

            unset($data['intention_id']);
            unset($data['times_id']);
            $volunteer_id = $this->model->change($user_id, $account_id, $data);

            //添加服务意向
            $volunteerApplyIntention = new VolunteerApplyIntention();
            $volunteerApplyIntention->interTableChange('volunteer_id', $volunteer_id, 'intention_id', $intention_id);
            //添加服务时间
            $volunteerApplyTime = new VolunteerApplyTime();
            $volunteerApplyTime->interTableChange('volunteer_id', $volunteer_id, 'times_id', $times_id);

            $system_id = $this->systemAdd('志愿者提交成功', $user_id, $account_id, 18, intval($volunteer_id), '志愿者提交成功，等待后台管理员审核');

            DB::commit();
            return $this->returnApi(200, "提交成功", true);
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->returnApi(202, $e->getMessage());
        }
    }

    /**
     * 撤销志愿者
     * @param token 
     */
    public function volunteerCancel()
    {
        $user_id = $this->request->user_info['id'];
        $res = $this->model->detail(null, $user_id);
        if (empty($res)) {
            return $this->returnApi(201, '网络错误');
        }

        if ($res->status == 2) {
            return $this->returnApi(201, '当前已是取消状态');
        }

        DB::beginTransaction();
        try {
            $res->status = 2;
            $res->save();

            $system_id = $this->systemAdd('志愿者撤销成功', $user_id, $res->account_id, 19, intval($res->id), '志愿者撤销成功，需要再次成为志愿者，需要重新提交申请！');

            // 提交事务
            DB::commit();
            return $this->returnApi(200, "撤销成功", true);
        } catch (\Exception $e) {
            // 回滚事务
            DB::rollBack();
            return $this->returnApi(202, $e->getMessage());
        }
    }
}
